import json
import re

import pymysql


## 栈找括号
def extract_all_contents(text, regex_pattern) -> []:
    contents = []
    pattern = re.compile(regex_pattern, re.IGNORECASE)  # 查找GROUP_CONCAT的起始位置
    start_positions = [m.start() for m in pattern.finditer(text)]

    for start_pos in start_positions:
        stack = []
        content = ''
        end_pos = None
        # 从GROUP_CONCAT后的第一个左括号开始
        for i, char in enumerate(text[start_pos:], start=start_pos):
            if char == '(':
                if not stack:  # 如果栈为空，说明是GROUP_CONCAT的最外层左括号
                    content_start = i + 1
                stack.append(char)
            elif char == ')':
                stack.pop()
                if not stack:  # 当栈为空时，说明遇到了最外层右括号
                    end_pos = i
                    break

        if end_pos is not None:  # 确保找到了完整的GROUP_CONCAT括号对
            contents.append(text[content_start:end_pos].strip())
    return contents


def task_config(db_config, task_name) -> str:
    connect = MysqlTool(db_config)
    row = connect.fetch_one(f"""select t.exe_json 
                         from di_vision.di_cdag_task_version t
                         JOIN di_vision.di_cdag_task_info b 
                         on t.task_id=b.id
                         where b.task_name ='{task_name}' and t.`status`=1 and b.schedule_name !='' and b.exec_flag='1'
    """)
    connect.close()
    exe_json = row.get("exe_json")
    if exe_json and len(exe_json) == 0:
        print("没有获取执行内容")
        exit(-1)
    query_sql = re.sub("&quot;", '"', exe_json)
    query_sql_json = json.loads(query_sql)
    tidb_sql = query_sql_json.get('tidbSql', '')
    # 删除单行注释且把sql 变成一行
    tidb_sql = re.sub("--.*|\\n|\\r|\\t", ' ', tidb_sql)
    # 删除多行注释
    tidb_sql = re.sub('/\*.*?\*/', "", tidb_sql)

    ## 替换双空格为单空格
    def replace_double_spaces(s):
        # 使用正则表达式替换两个或以上的空格为一个空格
        while '  ' in s:
            s = re.sub(r' {2,}', ' ', s)
        return s

    return replace_double_spaces(tidb_sql)


class MysqlTool:
    def __init__(self, db_config):
        """ 初始化数据库连接 """
        self.conn = pymysql.connect(db_config)
        self.cursor = self.conn.cursor(pymysql.cursors.DictCursor)

    def execute_sql(self, sql, params=None):
        """ 执行SQL语句 """
        try:
            self.cursor.execute(sql, params)
            self.conn.commit()
            print("SQL executed successfully")
            return self.cursor.fetchall() if self.cursor.description else None
        except Exception as e:
            print(f"Error occurred: {e}")
            self.conn.rollback()
            return None
        finally:
            self.cursor.close()

    def close(self):
        """ 关闭数据库连接 """
        self.conn.close()
        print("Connection closed")

    def fetch_one(self, sql, params=None):
        """ 查询单条数据 """
        self.cursor.execute(sql, params)
        return self.cursor.fetchone()

    def fetch_all(self, sql, params=None):
        """ 查询所有数据 """
        self.cursor.execute(sql, params)
        return self.cursor.fetchall()
